package aliyun

import (
	"cloudstation/util"
	"fmt"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type aliyun struct {
	Endpoint  string `validate:"required,url"`
	AccessID  string `validate:"required"`
	AccessKey string `validate:"required"`
	listner   oss.ProgressListener
}

// NewAliyun: 构建函数
func NewUploader(endpoint, accessID, accessKey string) (*aliyun, error) {
	al := &aliyun{
		Endpoint:  endpoint,
		AccessID:  accessID,
		AccessKey: accessKey,
		listner:   NewOssProgressListener(),
	}
	if err := util.Validate(al); err != nil {
		return nil, err
	}

	return al, nil
}

// UploadFile: 上传接口
func (p *aliyun) UploadFile(bucketName, objectKey, localFilePath string) error {
	bucket, err := p.getBucket(bucketName)
	if err != nil {
		return err
	}
	err = bucket.PutObjectFromFile(objectKey, localFilePath, oss.Progress(p.listner))
	if err != nil {
		return err
	}

	signedURL, err := bucket.SignURL(objectKey, oss.HTTPGet, 60*60*24)
	if err != nil {
		return fmt.Errorf("SignURL error, %s", err)
	}
	fmt.Printf("下载链接: %s\n", signedURL)
	fmt.Println("\n注意: 文件下载有效期为1天, 中转站保存时间为3天, 请及时下载")

	return nil
}

// getBucket： 获取Bucket
func (p *aliyun) getBucket(bucketName string) (*oss.Bucket, error) {
	if bucketName == "" {
		return nil, fmt.Errorf("upload bucket name required")
	}
	client, err := oss.New(p.Endpoint, p.AccessID, p.AccessKey)
	if err != nil {
		return nil, err
	}

	return client.Bucket(bucketName)

}
